<!--
 * @Author: Craft
 * @Date: 2024-08-18
 * @Description: 暗黑破坏神2重置版装备查询系统
-->
<template>
  <view class="d2r-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <u-search
        v-model="searchKeyword"
        placeholder="搜索装备名称或属性"
        :show-action="false"
        :clearabled="true"
        @search="handleSearch"
        @clear="handleClear"
        height="70rpx"
        bg-color="#0a0a0a"
        border-color="#333333"
        search-icon-color="#d4af37"
        color="#e0e0e0"
      ></u-search>
    </view>
    
    <!-- 筛选条件 -->
    <view class="filter-section">
      <scroll-view scroll-x="true" class="filter-scroll" show-scrollbar="false">
        <view class="filter-tabs">
          <view 
            class="filter-tab" 
            :class="{ active: activeType === type.value }" 
            v-for="type in itemTypes" 
            :key="type.value"
            @click="setActiveType(type.value)"
          >
            {{ type.label }}
          </view>
        </view>
      </scroll-view>
      
      <view class="filter-quality">
        <view 
          class="quality-tag" 
          :class="{ active: activeQuality === quality.value }" 
          v-for="quality in itemQualities" 
          :key="quality.value"
          @click="setActiveQuality(quality.value)"
        >
          {{ quality.label }}
        </view>
      </view>
      
      <view class="filter-actions">
        <view class="filter-action" @click="showLevelFilter = true">
          <text>等级: {{ levelFilter.min }}-{{ levelFilter.max }}</text>
          <u-icon name="arrow-down" size="14" color="#a0a0a0"></u-icon>
        </view>
        <view class="filter-action" @click="showSortOptions = true">
          <text>排序: {{ currentSortLabel }}</text>
          <u-icon name="arrow-down" size="14" color="#a0a0a0"></u-icon>
        </view>
      </view>
    </view>
    
    <!-- 装备列表 -->
    <view class="items-container">
      <view v-if="loading" class="d2r-loading">
        <u-loading-icon mode="circle" color="#d4af37"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="filteredItems.length === 0" class="d2r-empty">
        <u-icon name="info-circle" size="48" color="#a0a0a0"></u-icon>
        <text class="empty-text">没有找到符合条件的装备</text>
      </view>
      
      <view v-else class="items-list">
        <view 
          class="item-card" 
          v-for="item in filteredItems" 
          :key="item._id"
          @click="navigateToItemDetail(item._id)"
        >
          <view class="item-header">
            <view class="item-image-container" :class="'quality-border ' + getQualityClass(item.quality)">
              <image class="item-image" :src="item.image || '/static/items/default.png'" mode="aspectFit"></image>
            </view>
            <view class="item-title">
              <text class="item-name" :class="getQualityTextClass(item.quality)">{{ item.name }}</text>
              <text class="item-type">{{ item.type }}{{ item.subType ? ' - ' + item.subType : '' }}</text>
            </view>
          </view>
          
          <view class="item-info">
            <text class="item-level">需求等级: {{ item.levelRequire }}</text>
            <view class="item-attributes">
              <text class="item-attribute" v-for="(attr, index) in item.attributes.slice(0, 3)" :key="index">{{ attr }}</text>
              <text class="item-attribute more" v-if="item.attributes.length > 3">+{{ item.attributes.length - 3 }} 更多属性...</text>
            </view>
          </view>
          
          <view class="item-footer">
            <view class="item-stats">
              <view class="stat-item">
                <u-icon name="star" size="14" color="#a0a0a0"></u-icon>
                <text class="stat-text">{{ item.favCount || 0 }}</text>
              </view>
            </view>
            <view class="item-action">
              <u-icon name="arrow-right" size="14" color="#d4af37"></u-icon>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="load-more" @click="loadMoreItems">
        <text>加载更多</text>
      </view>
    </view>
    
    <!-- 等级筛选弹窗 -->
    <u-popup v-model="showLevelFilter" mode="bottom" border-radius="16">
      <view class="filter-popup">
        <view class="popup-header">
          <text class="popup-title">等级筛选</text>
          <u-icon name="close" size="20" @click="showLevelFilter = false"></u-icon>
        </view>
        <view class="level-slider">
          <text class="slider-label">最低等级: {{ levelFilter.min }}</text>
          <u-slider
            v-model="levelFilter.min"
            :min="1"
            :max="99"
            :step="1"
            active-color="#d4af37"
          ></u-slider>
          <text class="slider-label">最高等级: {{ levelFilter.max }}</text>
          <u-slider
            v-model="levelFilter.max"
            :min="1"
            :max="99"
            :step="1"
            active-color="#d4af37"
          ></u-slider>
        </view>
        <view class="popup-actions">
          <u-button text="重置" size="small" @click="resetLevelFilter"></u-button>
          <u-button text="确定" type="primary" size="small" @click="applyLevelFilter"></u-button>
        </view>
      </view>
    </u-popup>
    
    <!-- 排序选项弹窗 -->
    <u-popup v-model="showSortOptions" mode="bottom" border-radius="16">
      <view class="filter-popup">
        <view class="popup-header">
          <text class="popup-title">排序方式</text>
          <u-icon name="close" size="20" @click="showSortOptions = false"></u-icon>
        </view>
        <view class="sort-options">
          <view 
            class="sort-option" 
            :class="{ active: currentSort.field === option.field && currentSort.order === option.order }"
            v-for="option in sortOptions" 
            :key="`${option.field}-${option.order}`"
            @click="setSort(option)"
          >
            <text>{{ option.label }}</text>
            <u-icon v-if="currentSort.field === option.field && currentSort.order === option.order" name="checkmark" size="16" color="#d4af37"></u-icon>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { loadData } from '@/common/d2r-data'

// 数据
const items = ref([])
const filteredItems = ref([])
const loading = ref(true)
const hasMore = ref(false)
const pageSize = 20
const currentPage = ref(1)

// 搜索和筛选
const searchKeyword = ref('')
const activeType = ref('all')
const activeQuality = ref('all')
const levelFilter = ref({
  min: 1,
  max: 99
})

// 弹窗控制
const showLevelFilter = ref(false)
const showSortOptions = ref(false)

// 排序选项
const sortOptions = [
  { field: 'levelRequire', order: 'asc', label: '等级 (低到高)' },
  { field: 'levelRequire', order: 'desc', label: '等级 (高到低)' },
  { field: 'favCount', order: 'desc', label: '收藏数 (高到低)' },
  { field: 'name', order: 'asc', label: '名称 (A-Z)' }
]
const currentSort = ref(sortOptions[2]) // 默认按收藏数排序

// 装备类型
const itemTypes = [
  { value: 'all', label: '全部' },
  { value: '头盔', label: '头盔' },
  { value: '盔甲', label: '盔甲' },
  { value: '武器', label: '武器' },
  { value: '戒指', label: '戒指' },
  { value: '护身符', label: '护身符' },
  { value: '符文之语', label: '符文之语' }
]

// 装备品质
const itemQualities = [
  { value: 'all', label: '全部' },
  { value: '普通', label: '普通' },
  { value: '魔法', label: '魔法' },
  { value: '稀有', label: '稀有' },
  { value: '套装', label: '套装' },
  { value: '暗金', label: '暗金' }
]

// 计算当前排序标签
const currentSortLabel = computed(() => {
  return currentSort.value.label
})

// 监听筛选条件变化
watch([searchKeyword, activeType, activeQuality, levelFilter, currentSort], () => {
  currentPage.value = 1
  applyFilters()
}, { deep: true })

// 生命周期
onMounted(async () => {
  await loadItemsData()
})

// 加载装备数据
async function loadItemsData() {
  try {
    loading.value = true
    items.value = await loadData('items')
    applyFilters()
  } catch (error) {
    console.error('加载装备数据失败', error)
    uni.showToast({
      title: '加载装备数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 应用筛选条件
function applyFilters() {
  let result = [...items.value]
  
  // 搜索关键词
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => {
      // 搜索名称
      if (item.name.toLowerCase().includes(keyword)) {
        return true
      }
      
      // 搜索类型
      if (item.type.toLowerCase().includes(keyword)) {
        return true
      }
      
      // 搜索属性
      if (item.attributes && item.attributes.some(attr => attr.toLowerCase().includes(keyword))) {
        return true
      }
      
      return false
    })
  }
  
  // 类型筛选
  if (activeType.value !== 'all') {
    result = result.filter(item => item.type === activeType.value)
  }
  
  // 品质筛选
  if (activeQuality.value !== 'all') {
    result = result.filter(item => item.quality === activeQuality.value)
  }
  
  // 等级筛选
  result = result.filter(item => {
    const level = item.levelRequire || 1
    return level >= levelFilter.value.min && level <= levelFilter.value.max
  })
  
  // 排序
  result.sort((a, b) => {
    const fieldA = a[currentSort.value.field] || 0
    const fieldB = b[currentSort.value.field] || 0
    
    if (currentSort.value.order === 'asc') {
      return fieldA > fieldB ? 1 : -1
    } else {
      return fieldA < fieldB ? 1 : -1
    }
  })
  
  // 分页
  const totalItems = result.length
  hasMore.value = totalItems > currentPage.value * pageSize
  
  filteredItems.value = result.slice(0, currentPage.value * pageSize)
}

// 加载更多
function loadMoreItems() {
  currentPage.value++
  applyFilters()
}

// 处理搜索
function handleSearch() {
  applyFilters()
}

// 清除搜索
function handleClear() {
  searchKeyword.value = ''
  applyFilters()
}

// 设置装备类型
function setActiveType(type) {
  activeType.value = type
}

// 设置装备品质
function setActiveQuality(quality) {
  activeQuality.value = quality
}

// 应用等级筛选
function applyLevelFilter() {
  // 确保最小值不大于最大值
  if (levelFilter.value.min > levelFilter.value.max) {
    levelFilter.value.min = levelFilter.value.max
  }
  
  showLevelFilter.value = false
  applyFilters()
}

// 重置等级筛选
function resetLevelFilter() {
  levelFilter.value = {
    min: 1,
    max: 99
  }
}

// 设置排序方式
function setSort(option) {
  currentSort.value = option
  showSortOptions.value = false
}

// 跳转到装备详情
function navigateToItemDetail(itemId) {
  uni.navigateTo({
    url: `/pages-sub/database/item-detail?id=${itemId}`
  })
}

// 获取品质样式类
function getQualityClass(quality) {
  switch (quality?.toLowerCase()) {
    case '普通': return 'normal'
    case '魔法': return 'magic'
    case '稀有': return 'rare'
    case '套装': return 'set'
    case '暗金': return 'unique'
    case '工艺': return 'crafted'
    default: return ''
  }
}

// 获取品质文本样式类
function getQualityTextClass(quality) {
  switch (quality?.toLowerCase()) {
    case '普通': return 'text-normal'
    case '魔法': return 'text-magic'
    case '稀有': return 'text-rare'
    case '套装': return 'text-set'
    case '暗金': return 'text-unique'
    case '工艺': return 'text-crafted'
    default: return ''
  }
}
</script>

<style lang="scss" scoped>
@import '../../common/d2r-theme.scss';
.d2r-container {
  min-height: 100vh;
  padding-bottom: 30px;
}

// 搜索栏
.search-bar {
  padding: 10px 15px;
  background-color: $d2r-bg-darker;
  position: sticky;
  top: 0;
  z-index: 10;
}

// 筛选区域
.filter-section {
  background-color: $d2r-bg-darker;
  padding-bottom: 10px;
  
  .filter-scroll {
    width: 100%;
    white-space: nowrap;
    
    .filter-tabs {
      display: inline-flex;
      padding: 0 15px;
      
      .filter-tab {
        padding: 8px 15px;
        margin-right: 10px;
        font-size: 14px;
        color: $d2r-text-muted;
        position: relative;
        
        &.active {
          color: $d2r-gold;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 2px;
            background-color: $d2r-gold;
          }
        }
      }
    }
  }
  
  .filter-quality {
    display: flex;
    flex-wrap: wrap;
    padding: 10px 15px;
    
    .quality-tag {
      padding: 4px 10px;
      border-radius: 12px;
      font-size: 12px;
      background-color: $d2r-bg-dark;
      color: $d2r-text-muted;
      margin-right: 8px;
      margin-bottom: 8px;
      
      &.active {
        background-color: $d2r-gold;
        color: $d2r-bg-dark;
      }
    }
  }
  
  .filter-actions {
    display: flex;
    justify-content: space-between;
    padding: 0 15px;
    
    .filter-action {
      display: flex;
      align-items: center;
      font-size: 12px;
      color: $d2r-text;
      background-color: $d2r-bg-dark;
      padding: 6px 12px;
      border-radius: 4px;
      
      u-icon {
        margin-left: 5px;
      }
    }
  }
}

// 装备列表
.items-container {
  padding: 10px 15px;
  
  .items-list {
    .item-card {
      background-color: $d2r-bg-darker;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 10px;
      
      .item-header {
        display: flex;
        margin-bottom: 10px;
        
        .item-image-container {
          width: 50px;
          height: 50px;
          padding: 3px;
          background-color: $d2r-bg-dark;
          border-radius: 4px;
          margin-right: 10px;
          
          .item-image {
            width: 100%;
            height: 100%;
          }
        }
        
        .item-title {
          flex: 1;
          
          .item-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 4px;
            display: block;
          }
          
          .item-type {
            font-size: 12px;
            color: $d2r-text-muted;
          }
        }
      }
      
      .item-info {
        margin-bottom: 10px;
        
        .item-level {
          font-size: 12px;
          color: $d2r-text-muted;
          margin-bottom: 5px;
          display: block;
        }
        
        .item-attributes {
          .item-attribute {
            font-size: 14px;
            color: $d2r-text;
            display: block;
            margin-bottom: 2px;
            
            &.more {
              color: $d2r-text-muted;
              font-style: italic;
            }
          }
        }
      }
      
      .item-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .item-stats {
          display: flex;
          
          .stat-item {
            display: flex;
            align-items: center;
            margin-right: 15px;
            
            .stat-text {
              font-size: 12px;
              color: $d2r-text-muted;
              margin-left: 4px;
            }
          }
        }
      }
    }
  }
  
  .load-more {
    text-align: center;
    padding: 15px 0;
    color: $d2r-gold;
    font-size: 14px;
  }
}

// 弹窗样式
.filter-popup {
  background-color: $d2r-bg-dark;
  padding: 20px;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .popup-title {
      font-size: 16px;
      color: $d2r-gold;
      font-weight: bold;
    }
  }
  
  .level-slider {
    margin-bottom: 20px;
    
    .slider-label {
      font-size: 14px;
      color: $d2r-text;
      margin-bottom: 10px;
      display: block;
    }
  }
  
  .sort-options {
    .sort-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid $d2r-border;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.active {
        color: $d2r-gold;
      }
    }
  }
  
  .popup-actions {
    display: flex;
    justify-content: space-between;
  }
}

// 品质文本颜色
.text-normal {
  color: $quality-normal;
}

.text-magic {
  color: $quality-magic;
}

.text-rare {
  color: $quality-rare;
}

.text-set {
  color: $quality-set;
}

.text-unique {
  color: $quality-unique;
}

.text-crafted {
  color: $quality-crafted;
}
</style>